package com.bignerdranch.travelcommunity.ui.adapters

import android.content.Context
<<<<<<< HEAD
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
=======
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import android.widget.ProgressBar
>>>>>>> f9d31c9... first
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentManager
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bignerdranch.tclib.LogUtil
import com.bignerdranch.tclib.LogUtil.eee
import com.bignerdranch.tclib.LogUtil.eeee
<<<<<<< HEAD
=======
import com.bignerdranch.tclib.LogUtil.eeeee
import com.bignerdranch.tclib.LogUtil.videoLog
>>>>>>> f9d31c9... first
import com.bignerdranch.tclib.data.db.entity.CommentsMsg
import com.bignerdranch.tclib.data.db.entity.PersonDynamic
import com.bignerdranch.tclib.utils.DeviceUtils
import com.bignerdranch.travelcommunity.R
import com.bignerdranch.travelcommunity.base.BaseViewModel
import com.bignerdranch.travelcommunity.base.Message
import com.bignerdranch.travelcommunity.databinding.ItemRecyclerviewVideoLayoutBinding
<<<<<<< HEAD
=======
import com.bignerdranch.travelcommunity.task.DownLoadObserver
import com.bignerdranch.travelcommunity.task.DownloadInfo
import com.bignerdranch.travelcommunity.task.DownloadManager
>>>>>>> f9d31c9... first
import com.bignerdranch.travelcommunity.task.TaskServer
import com.bignerdranch.travelcommunity.tcvideoplayer.TCPlayer
import com.bignerdranch.travelcommunity.tcvideoplayer.TCPlayer.OnNetChangeListener
import com.bignerdranch.travelcommunity.ui.dynamic.CommentsDialog
import com.bignerdranch.travelcommunity.ui.dynamic.viewModels.PersonDynamicViewModel
import com.bignerdranch.travelcommunity.ui.user.FriendFragment
import com.bignerdranch.travelcommunity.util.ToastUtil.show
<<<<<<< HEAD
import java.lang.ref.WeakReference
=======
import io.reactivex.disposables.Disposable
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentHashMap
>>>>>>> f9d31c9... first


class VideoViewAdapter(val context: Context,
                       val fragmentManager: FragmentManager,
                       val _viewModel:PersonDynamicViewModel
): ListAdapter<PersonDynamic, RecyclerView.ViewHolder>(
Diff()
) {
<<<<<<< HEAD
    var mHeight = 0
    private var playPosition = 0
    private var progress = 0
    private var currentPage = 0
    private val recycle =  ArrayList<VideoViewHolder>()
    private var limit = 1

=======

    private var playPosition = 0
    private var progress = 0
    private var currentPage = 0
    private var initVideo = false
    private var mHeight = 0
    private var mWidth = 0
    private var position = 0
    private val recycle =  ArrayList<VideoViewHolder>()

    private val players =  ConcurrentHashMap<String,TCPlayer>()

    private  var currentPlayer:TCPlayer? = null

    private var limit = 1

    private fun  getPlayer(url:String) = players[url]

    private fun  putPlayer(url: String, tcPlayer: TCPlayer){
        players[url] = tcPlayer
    }

>>>>>>> f9d31c9... first

    fun setPlayPosition(position: Int): VideoViewAdapter {
        playPosition = position
        return this
    }

<<<<<<< HEAD

=======
>>>>>>> f9d31c9... first
    fun setCurrentPage(page:Int):VideoViewAdapter{
        currentPage = page
        return this
    }

    fun setProgress(progress: Int): VideoViewAdapter {
        this.progress = progress
        return this
    }


<<<<<<< HEAD
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
       val l = VideoViewHolder(
            ItemRecyclerviewVideoLayoutBinding.inflate(LayoutInflater.from(context),parent,false))
        recycle.add(l)
=======
    fun prepareInBackground(urls:List<String>){
         val times =  if(urls.size >=5)  5 else urls.size

          repeat(times){
               val url = urls[position++]
               val tcPlayer = TCPlayer(context)
              putPlayer(url, tcPlayer)
              videoLog("url"+url+"tcplayer"+tcPlayer)
              TaskServer.execute {
                tcPlayer.toPrepare(url)
              }
        }

    }

    fun checkDiff(){

    }


    override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
        super.onViewAttachedToWindow(holder)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

       val l = VideoViewHolder(ItemRecyclerviewVideoLayoutBinding.inflate(LayoutInflater.from(context),parent,false))
        recycle.add(l)

>>>>>>> f9d31c9... first
        return l
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val data = getItem(position)
<<<<<<< HEAD
=======
        if(position%5==0){
            videoLog("开始准备..")
             prepareInBackground(currentList.toList().map { it.videoUrl!! })
        }
>>>>>>> f9d31c9... first
        (holder as VideoViewHolder).update(position,data)
    }


<<<<<<< HEAD

=======
>>>>>>> f9d31c9... first
    fun clearAllView() {
      recycle.forEach {
          it.onDestroy()
      }
      recycle.clear()
    }

    fun clearItemView(position:Int){
      if(position > recycle.size) throw ArrayIndexOutOfBoundsException()
        recycle[position].onDestroy()
        recycle.removeAt(position)
    }




<<<<<<< HEAD
=======


>>>>>>> f9d31c9... first
    inner class VideoViewHolder(private val  binding: ItemRecyclerviewVideoLayoutBinding)
        : RecyclerView.ViewHolder(binding.root){

        private val playerLayout: ConstraintLayout = binding.layoutControl
<<<<<<< HEAD
        var tcPlayer = binding.adapterSuperVideo
=======
        //var tcPlayer = binding.adapterSuperVideo
        var videoView = binding.videoView
       private lateinit var tcPlayer:TCPlayer
>>>>>>> f9d31c9... first
        val progressBar  = binding.progressBar
        val like = binding.like
        val comments = binding.comments
        private val headProfile = binding.headUrl
        private val addFocus = binding.addFocus
        val share =  binding.share
        private var mPosition = 0
        private var url: String? = null
<<<<<<< HEAD
        private var netChange = false
        private lateinit  var personDynamic: PersonDynamic




        init {
            val layoutParams = playerLayout.layoutParams

            when(BaseViewModel.typeScreen) {
                Message.FULL_SCREEN -> {
                    eee("FULL_SCREEN")
                    layoutParams.height =
                        DeviceUtils.deviceHeight(context) + 2*(context.resources.getDimensionPixelSize(
                            R.dimen.statusBar
                        ))
                }
                Message.NOT_FULL_SCREEN -> {
                    eee("NOT_FULL_SCREEN")
                    layoutParams.height = DeviceUtils.deviceHeight(context) + (context.resources.getDimensionPixelSize(
                        R.dimen.action_pic_size
                    ))
                }
            }

            playerLayout.layoutParams = layoutParams

            var  onNetChangeListener =  object : OnNetChangeListener {
                override fun onWifi() {
                    eeee("onWifi")
                    if (netChange && mPosition == playPosition) {
                        tcPlayer.toPrepare(url)
                        play(progress)
                    }
                    netChange = false
                }

                override fun onMobile() {
                    if (netChange && mPosition == playPosition) {
                        tcPlayer.toPrepare(url)
                        eeee("onMobile")
                        play(tcPlayer.currentPosition)
                    }

                    netChange = false
                }

                override fun onDisConnect() {

                }

                override fun onNoAvailable() {
                    netChange = true

                }
            }

            val onProgressChangedListener = object :TCPlayer.OnProgressChangedListener{
                override fun progressDuration(duration: Int) {
                }

                override fun progressPosition(progress: Int) {
                    progressBar.progress = progress
                }
            }

=======
        private lateinit  var personDynamic: PersonDynamic

        private   val onProgressChangedListener = object :TCPlayer.OnProgressChangedListener{
            override fun progressDuration(duration: Int) {

            }

            override fun progressPosition(progress: Int) {
                progressBar.progress = progress
            }
        }

        private  val onNetChangeListener = object :TCPlayer.OnNetChangeListener{

            private var  netChange  = false

            override fun onWifi() {
                if (netChange && mPosition == playPosition) {
                    tcPlayer.toPrepare(url)
                    tcPlayer.toStart(tcPlayer.currentPosition)
                }
                netChange = false
            }

            override fun onMobile() {
                if (netChange && mPosition == playPosition) {
                    tcPlayer.toPrepare(url)
                    tcPlayer.toStart(tcPlayer.currentPosition)
                }
                netChange = false
            }

            override fun onDisConnect() {

            }

            override fun onNoAvailable() {
                netChange = true
            }
        }

        init {
            val layoutParams = playerLayout.layoutParams

            when(BaseViewModel.typeScreen) {
                Message.FULL_SCREEN -> {
                    eee("FULL_SCREEN")

                     mHeight =    DeviceUtils.deviceHeight(context) + 2*(context.resources.getDimensionPixelSize(
                            R.dimen.statusBar
                        ))
                    layoutParams.height = mHeight
                }
                Message.NOT_FULL_SCREEN -> {
                    eee("NOT_FULL_SCREEN")

                        mHeight = DeviceUtils.deviceHeight(context) + (context.resources.getDimensionPixelSize(
                        R.dimen.action_pic_size
                    ))
                    layoutParams.height = mHeight
                }
            }
                playerLayout.layoutParams = layoutParams
>>>>>>> f9d31c9... first

            headProfile.setOnClickListener {
                val friendFragment1 =  FriendFragment(_viewModel = _viewModel)
                friendFragment1.setFriendId(personDynamic.userId)
                _viewModel.toQueryFriendById(personDynamic.userId)
                friendFragment1.show(fragmentManager,"")
            }

            comments.setOnClickListener {
                CommentsDialog(_viewModel = _viewModel,dynamicId = personDynamic.id)
                    .show(fragmentManager.beginTransaction(),"commentsDialog")
            }

            share.setOnClickListener {
                show("share")
                 checkLogin(it){

                 }
            }

            like.setOnClickListener  {
                show("like")
                 checkLogin(it){
                     _viewModel.toAddLike(personDynamic.id,0)
                 }
            }

            addFocus.setOnClickListener {
                show("add foucs")
                checkLogin(it) {
                    _viewModel.toAddFriend(personDynamic.userId)
                }
            }
<<<<<<< HEAD

=======
        }

        fun initPlayer(){

            tcPlayer = getPlayer(url!!)!!

            tcPlayer.url = url
>>>>>>> f9d31c9... first
            tcPlayer.setOnProgressChangedListener(onProgressChangedListener)
                .setOnNetChangeListener(onNetChangeListener)
                .setDoubleClickListener {  }
                .onPrepared { if(mPosition == playPosition) play(progress) }
                .onComplete { play(0) }
                .setNetChangeListener(true)
                .setBottomControl(true)
                .setLive(false)
                .setSupportGesture(false).setShowTopControl(false)
<<<<<<< HEAD

=======
             val layout = FrameLayout.LayoutParams(MATCH_PARENT,mHeight)
            layout.gravity =Gravity.CENTER
            tcPlayer.layoutParams =  layout

             videoView.addView(tcPlayer)
>>>>>>> f9d31c9... first
        }


        fun play(progress: Int) {
<<<<<<< HEAD
            TaskServer.execute {
                tcPlayer.toStart(progress)
            }
=======
           // prepare()
           TaskServer.execute {
             //  prepare()
            tcPlayer.toStart(progress)
            }


>>>>>>> f9d31c9... first
        }

        fun pause() {
            tcPlayer.pauseLater()
        }

        fun release() {
            tcPlayer.release()
        }

        fun onResume() {
            tcPlayer.onResume()
<<<<<<< HEAD
        }

        fun prepare(){
                    tcPlayer.toPrepare(url)
=======

        }

        fun removeView(url: String){
            val tcPlayer = getPlayer(url)
            LogUtil.videoLog("tcplay $tcPlayer")
            videoView.removeView(tcPlayer)
        }

        fun prepare(){
             tcPlayer.toPrepare(url)
>>>>>>> f9d31c9... first
        }

        fun currentProgress(): Int {
            return tcPlayer.currentPosition
        }

        fun onDestroy() {
            release()
            eeee("onDestroy")
            tcPlayer.onDestroy()
            tcPlayer.setDoubleClickListener(null)
            tcPlayer.setOnNetChangeListener(null)

        }

        fun update(position: Int,personDynamic: PersonDynamic) {
            mPosition = position
            this.personDynamic  = personDynamic
            binding.personDynamic = personDynamic
            url = ""+personDynamic.videoUrl
<<<<<<< HEAD
            tcPlayer.url = url
            eee("name ${personDynamic.userNickName}"+url)
            prepare()
=======
            initPlayer()
>>>>>>> f9d31c9... first
            binding.executePendingBindings()
        }

        fun checkLogin(view: View, doWorkOk:()->Unit){
            if(_viewModel.isLogin.value == false){
                view.findNavController().navigate(R.id.login_and_register)
            }else{
                doWorkOk()
            }
        }
<<<<<<< HEAD

=======
>>>>>>> f9d31c9... first
    }

    class Diff : DiffUtil.ItemCallback<PersonDynamic>(){
        override fun areContentsTheSame(oldItem: PersonDynamic, newItem: PersonDynamic): Boolean {
            LogUtil.w("比较")
            return oldItem == newItem
        }

        override fun areItemsTheSame(oldItem: PersonDynamic, newItem: PersonDynamic): Boolean {
            LogUtil.w("比较")
            return oldItem.id == newItem.id
        }
    }
}


/*
class VideoViewAdapter(val context:Context): BaseRecyclerViewAdapter<String>() {
    var mHeight = 0
    private var playPosition = 0
    private var progress = 0


    fun setPlayPosition(position: Int): VideoViewAdapter {
        playPosition = position
        return this
    }

    fun setProgress(progress: Int): VideoViewAdapter {
        this.progress = progress
        return this
    }

    override fun bindData(holder: BaseRecyclerViewHolder?, position: Int) {
         val  data = getItemData(position)
        LogUtil.ee("aa 又创建了 $position")
        (holder as VideoViewHolder).update(position,data)
    }

    override fun createItem(parent: ViewGroup?, viewType: Int): BaseRecyclerViewHolder {
        val view =  LayoutInflater.from(context).inflate(R.layout.item_recyclerview_video_layout,null)
        LogUtil.ee("aa bb yya 又创建了 ")
        return VideoViewHolder(view)
    }





    inner class VideoViewHolder(view: View)
       : BaseRecyclerViewHolder(view) {

        lateinit var playerControlLayout: RelativeLayout
        var playerLayout: ConstraintLayout = itemView.findViewById(R.id.layoutControl)
        private  var tcPlayer: TCPlayer = itemView.findViewById(R.id.adapter_super_video)
        lateinit var cover: ImageView
        var progressBar: ProgressBar = itemView.findViewById(R.id.progressBar)
        private var mPosition = 0
        private var url: String? = null
        private var netChange = false
        private var hasCreated = false
  //  下50dp  上30dp 80*1.5
        init {


            val layoutParams = playerLayout.layoutParams
            layoutParams.height = (DeviceUtils.deviceHeight(context)-30*2).toInt()
            playerLayout.layoutParams = layoutParams

            val  onNetChangeListener =  object : OnNetChangeListener {
               override fun onWifi() {
                   if (netChange && mPosition == playPosition) {
                       tcPlayer.toPrepare(url)
                       play(progress)
                   }
                   netChange = false
               }

               override fun onMobile() {
                   if (netChange && mPosition == playPosition) {
                       tcPlayer.toPrepare(url)
                       play(tcPlayer.currentPosition)
                   }

                   netChange = false
               }

               override fun onDisConnect() {

               }

               override fun onNoAvailable() {
                   netChange = true

               }
           }

       val onProgressChangedListener = object :TCPlayer.OnProgressChangedListener{
          override fun progressDuration(duration: Int) {
              LogUtil.eee("duration $duration")
          }

          override fun progressPosition(progress: Int) {
              LogUtil.eee("progress eeeee$progress")
              progressBar.progress = progress

          }
      }



        tcPlayer.setOnProgressChangedListener(onProgressChangedListener)
            .setOnNetChangeListener(onNetChangeListener)
            .setDoubleClickListener {  }
            .onPrepared { if(mPosition == playPosition) play(progress) }
            .onComplete { play(0) }
            .setNetChangeListener(true)
            .setLive(false)
            .setSupportGesture(false).setShowTopControl(false)

  }

        fun play(progress: Int) {
            tcPlayer.toStart(progress)
        }

        fun pause() {
            tcPlayer.pauseLater()
        }

        fun release() {
            tcPlayer.release()
        }

        fun onResume() {
            tcPlayer.onResume()
        }

        fun currentProgress(): Int {
            return tcPlayer.currentPosition
        }

        fun onDestroy() {
            release()
            tcPlayer.onDestroy()
        }

        fun update(position: Int,url:String) {
                mPosition = position
                this.url = url
                tcPlayer.url = url
                tcPlayer.toPrepare(url)
        }

         override fun getView(): View {
             return itemView
         }
    }




}
*/

